// 科目维度知识点画像页面交互功能
document.addEventListener('DOMContentLoaded', function() {
    // 初始化进度条动画
    initProgressBars();

    // 绑定知识点卡片交互
    bindKnowledgeCardEvents();

    // 初始化排序功能
    initSortFunctionality();

    // 初始化筛选功能
    initFilterFunctionality();

    // 初始化图表数据
    initChartData();

    // 绑定分析报告交互
    bindAnalysisReportEvents();
});

// 初始化进度条动画
function initProgressBars() {
    const progressBars = document.querySelectorAll('.knowledge-progress-bar');
    progressBars.forEach(bar => {
        const width = bar.style.width;
        bar.style.width = '0';
        setTimeout(() => {
            bar.style.width = width;
        }, 300);
    });
}

// 绑定知识点卡片交互
function bindKnowledgeCardEvents() {
    const knowledgeCards = document.querySelectorAll('.knowledge-card');

    knowledgeCards.forEach(card => {
        // 点击卡片跳转到详情页
        card.addEventListener('click', function() {
            const knowledgeId = this.dataset.knowledgeId;
            if (knowledgeId) {
                window.location.href = `/analysis/knowledge-point/${knowledgeId}/`;
            }
        });

        // 悬停效果
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateX(5px)';
            this.style.boxShadow = '0 4px 15px rgba(0, 0, 0, 0.1)';
        });

        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateX(0)';
            this.style.boxShadow = 'none';
        });
    });
}

// 初始化排序功能
function initSortFunctionality() {
    const sortSelect = document.getElementById('sortKnowledge');
    if (sortSelect) {
        sortSelect.addEventListener('change', function() {
            sortKnowledgePoints(this.value);
        });
    }
}

// 排序知识点
function sortKnowledgePoints(sortBy) {
    const container = document.querySelector('.knowledge-grid');
    const knowledgeCards = Array.from(document.querySelectorAll('.knowledge-card'));

    knowledgeCards.sort((a, b) => {
        const aMastery = parseFloat(a.dataset.mastery);
        const bMastery = parseFloat(b.dataset.mastery);
        const aName = a.querySelector('.knowledge-name').textContent;
        const bName = b.querySelector('.knowledge-name').textContent;

        switch (sortBy) {
            case 'mastery-asc':
                return aMastery - bMastery;
            case 'mastery-desc':
                return bMastery - aMastery;
            case 'name-asc':
                return aName.localeCompare(bName);
            case 'name-desc':
                return bName.localeCompare(aName);
            default:
                return 0;
        }
    });

    // 重新插入排序后的元素
    knowledgeCards.forEach(card => {
        container.appendChild(card);
    });

    showNotification(`已按${getSortLabel(sortBy)}排序`, 'info');
}

// 获取排序标签
function getSortLabel(sortBy) {
    const labels = {
        'mastery-asc': '掌握度升序',
        'mastery-desc': '掌握度降序',
        'name-asc': '名称升序',
        'name-desc': '名称降序'
    };
    return labels[sortBy] || '默认';
}

// 初始化筛选功能
function initFilterFunctionality() {
    const masteryFilter = document.getElementById('masteryFilter');
    const statusFilter = document.getElementById('statusFilter');

    if (masteryFilter) {
        masteryFilter.addEventListener('change', function() {
            applyFilters();
        });
    }

    if (statusFilter) {
        statusFilter.addEventListener('change', function() {
            applyFilters();
        });
    }
}

// 应用筛选
function applyFilters() {
    const masteryFilter = document.getElementById('masteryFilter');
    const statusFilter = document.getElementById('statusFilter');

    const masteryLevel = masteryFilter ? masteryFilter.value : '';
    const status = statusFilter ? statusFilter.value : '';

    const knowledgeCards = document.querySelectorAll('.knowledge-card');

    knowledgeCards.forEach(card => {
        const cardMastery = card.dataset.mastery;
        const cardStatus = card.dataset.status;

        let showCard = true;

        // 掌握度筛选
        if (masteryLevel) {
            const masteryNum = parseFloat(cardMastery);
            switch (masteryLevel) {
                case 'excellent':
                    showCard = showCard && masteryNum >= 0.8;
                    break;
                case 'good':
                    showCard = showCard && masteryNum >= 0.6 && masteryNum < 0.8;
                    break;
                case 'average':
                    showCard = showCard && masteryNum >= 0.4 && masteryNum < 0.6;
                    break;
                case 'poor':
                    showCard = showCard && masteryNum < 0.4;
                    break;
            }
        }

        // 状态筛选
        if (status && cardStatus !== status) {
            showCard = false;
        }

        card.style.display = showCard ? '' : 'none';
    });

    updateVisibleCount();
}

// 更新可见数量
function updateVisibleCount() {
    const visibleCards = document.querySelectorAll('.knowledge-card[style=""]').length;
    const totalCards = document.querySelectorAll('.knowledge-card').length;

    const countElement = document.getElementById('visibleCount');
    if (countElement) {
        countElement.textContent = `显示 ${visibleCards} / ${totalCards} 个知识点`;
    }
}

// 初始化图表数据
function initChartData() {
    // 这里可以初始化掌握度分布图表
    // 使用Chart.js或其他图表库
    initMasteryDistributionChart();
}

// 初始化掌握度分布图表
function initMasteryDistributionChart() {
    const ctx = document.getElementById('masteryDistributionChart');
    if (!ctx) return;

    // 这里使用Chart.js创建饼图
    // 示例代码，需要引入Chart.js库
    /*
    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['优秀', '良好', '一般', '薄弱'],
            datasets: [{
                data: [
                    document.querySelector('[data-mastery-level="excellent"]').dataset.count,
                    document.querySelector('[data-mastery-level="good"]').dataset.count,
                    document.querySelector('[data-mastery-level="average"]').dataset.count,
                    document.querySelector('[data-mastery-level="poor"]').dataset.count
                ],
                backgroundColor: [
                    '#28a745',
                    '#17a2b8',
                    '#ffc107',
                    '#dc3545'
                ]
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
    */
}

// 绑定分析报告交互
function bindAnalysisReportEvents() {
    const insightItems = document.querySelectorAll('.insight-item');

    insightItems.forEach(item => {
        item.addEventListener('click', function() {
            this.classList.toggle('expanded');

            const description = this.querySelector('.insight-description');
            if (this.classList.contains('expanded')) {
                description.style.maxHeight = description.scrollHeight + 'px';
            } else {
                description.style.maxHeight = '3em';
            }
        });

        // 初始设置描述文本高度
        const description = item.querySelector('.insight-description');
        description.style.maxHeight = '3em';
        description.style.overflow = 'hidden';
        description.style.transition = 'max-height 0.3s ease';
    });
}

// 导出科目数据
function exportSubjectData() {
    const subjectName = document.querySelector('.subject-title').textContent;
    const knowledgeCards = document.querySelectorAll('.knowledge-card');

    const exportData = {
        subject: subjectName,
        exportTime: new Date().toISOString(),
        totalPoints: knowledgeCards.length,
        knowledgePoints: []
    };

    knowledgeCards.forEach(card => {
        const name = card.querySelector('.knowledge-name').textContent;
        const mastery = card.querySelector('.mastery-badge').textContent;
        const status = card.dataset.status;

        exportData.knowledgePoints.push({
            name: name,
            mastery: mastery,
            status: status,
            knowledgeId: card.dataset.knowledgeId
        });
    });

    const dataStr = JSON.stringify(exportData, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});

    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `subject-${subjectName.replace(/\s+/g, '-')}-data.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    URL.revokeObjectURL(url);

    showNotification('科目数据导出成功！', 'success');
}

// 显示通知
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show`;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 300px;
    `;
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(notification);

    // 自动移除通知
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}

// 初始化所有功能
function initializeAll() {
    initProgressBars();
    bindKnowledgeCardEvents();
    initSortFunctionality();
    initFilterFunctionality();
    initChartData();
    bindAnalysisReportEvents();
    updateVisibleCount();
}

// 添加到全局作用域
window.exportSubjectData = exportSubjectData;

// 页面加载完成后初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeAll);
} else {
    initializeAll();
}